//
//  NewDeviceViewController.m
//  Demo
//
//  Created by Echo on 13-10-17.
//

#import "NewWifiViewController.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import "FirstTimeConfig.h"
#import "PokerControlClient.h"

@interface NewDeviceViewController (){
    NSTimer *timer;
}
@end

@implementation NewDeviceViewController
@synthesize wifissid,udpSocket;
@synthesize config;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [NC addObserver:self selector:@selector(stopUdpData) name:StopUdpData object:nil];
        [NC addObserver:self selector:@selector(stopUdpData) name:Stop_SOCKET_UdpData object:nil];
        [NC addObserver:self selector:@selector(resignActive) name:NOTI_RESIGN_ACTIVE object:nil];
        [NC addObserver:self selector:@selector(becomeActive) name:NOTI_BECOME_ACTIVE object:nil];
    }
    return self;
}
- (void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag
{
	// You could add checks here
}

- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error
{
	// You could add checks here
}

- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock
     didReceiveData:(NSData *)data
            withTag:(long)tag
           fromHost:(NSString *)host
               port:(UInt16)port
{
	NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	if (msg)
	{
        NSLog(@"msg : %@", msg);
	}
	else
	{
        NSLog(@"RECV: Unknown message from: %@:%hu", host, port);
	}
	
//	[udpSocket receiveWithTimeout:-1 tag:0];
	return YES;
}


-(void)refresh{
    
}
- (NSString *)currentWifiSSID {
    // Does not work on the simulator.
    NSString *ssid = nil;
    NSArray *ifs = (__bridge  id)CNCopySupportedInterfaces();
    NSLog(@"ifs:%@",ifs);
    for (NSString *ifnam in ifs) {
        NSDictionary *info = (__bridge id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        NSLog(@"allKeys：%@",[info  allKeys]);
        NSLog(@"allValues：%@",[info  allValues]);
        if (info[@"SSID"]) {
            ssid = info[@"SSID"];
        }
    }
    return ssid;
}
- (void)viewDidLoad
{
    self.title = STR(@"添加新设备");
    if ([Global curLanguageEn]) {
        self.title = @"Add New Device";
    }
    [super viewDidLoad];
    
    UIBarButtonItem *rightItem = [UIBarButtonItem backImageBarButtonItem:[UIImage imageNamed:@"reflesh.png"] target:self action:@selector(refresh)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    UIButton *bgBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [bgBtn addTarget:self action:@selector(bgBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bgBtn];
    
    self.wifissid = [self currentWifiSSID];
    for (int i=0; i<2; i++) {
        UIImage *image = IMG(@"new_device_bg.png");
        UIImageView *bg = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth-image.size.width/2)/2, 50+i*50, image.size.width/2, image.size.height/2)];
        bg.userInteractionEnabled = YES;
        bg.image = image;
        [self.view addSubview:bg];
        
        UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(60, 2, 150, bg.frame.size.height-4)];
        tf.returnKeyType = UIReturnKeyDone;
        tf.backgroundColor = [UIColor whiteColor];
        tf.font = [UIFont systemFontOfSize:14];
        [bg addSubview:tf];
        tf.delegate = self;
        
        GoodLabel *descLabel = [GoodLabel labelWithFont:14 title:@"WIFI："];
        descLabel.textColor = [UIColor blackColor];
        descLabel.frame = CGRectMake(15, 0, kScreenWidth, bg.frame.size.height);
        [bg addSubview:descLabel];
        if (i == 0) {
            m_tf1 = tf;
            if ([wifissid length] > 0) {
                tf.text = wifissid;
            }
            tf.returnKeyType = UIReturnKeyNext;
        }
        if (i == 1) {
            descLabel.text = STR(@"密码：");
            m_tf2 = tf;
            if ([Global curLanguageEn]) {
                descLabel.text = @"PW：";
            }
            NSString *PASSWORD = [UD objectForKey:WIFI_PASSWORD];
            m_tf2.text = PASSWORD;
            tf.enablesReturnKeyAutomatically = YES;
            tf.secureTextEntry = YES;
        }
    }
    
    UIButton *passwordBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 150, 30+100, 30)];
    passwordBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    passwordBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
    [passwordBtn setTitle:STR(@"显示密码") forState:UIControlStateNormal];
    if ([Global curLanguageEn]) {
        passwordBtn.frame = CGRectMake(20, 150, 30+100+60, 30);
        [passwordBtn setTitle:@"Show the password" forState:UIControlStateNormal];
    }
    [passwordBtn setImage:IMG(@"password_dot.png") forState:UIControlStateNormal];
    [passwordBtn setImage:IMG(@"password_dot_select.png") forState:UIControlStateSelected];
    [passwordBtn addTarget:self action:@selector(passwordBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:passwordBtn];
    
    UIButton *schemeBtn = [[UIButton alloc] initWithFrame:CGRectMake((kScreenWidth-197)/2, 200, 197, 30)];
    schemeBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [schemeBtn setTitle:STR(@"开始配置") forState:UIControlStateNormal];
    if ([Global curLanguageEn]) {
        [schemeBtn setTitle:@"Start configure" forState:UIControlStateNormal];
    }
    [schemeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [schemeBtn setBackgroundImage:IMG(@"APP_link_btn.png") forState:UIControlStateNormal];
    [schemeBtn addTarget:self action:@selector(schemeBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:schemeBtn];
}
#pragma -
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == m_tf1) {
        [m_tf2 becomeFirstResponder];
    }else if(textField == m_tf2){
        [textField resignFirstResponder];
    }
    return YES;
}

-(void)bgBtnPressed:(UIButton*)btn{
    [m_tf1 resignFirstResponder];
    [m_tf2 resignFirstResponder];
}
-(void)passwordBtnPressed:(UIButton*)btn{
    [btn setSelected:!btn.selected];
    if (!btn.selected) {
        [m_tf2 setSecureTextEntry:YES];
    }else{
        [m_tf2 setSecureTextEntry:NO];
    }
    
    NSLog(@"%d", m_tf2.secureTextEntry);
}

- (IBAction)incrementProgress:(id)sender
{
    if (progressView.progress == 0) {
        progressView.progress = 0.01;
    }else{
        progressView.progress += .01;
    }
    
    float value = progressView.progress*100;
    int nValue = value;
    
    
    progressLabel.text = [NSString stringWithFormat:@"%d%%", nValue];
    if (nValue == 65) {
        if (!isSendUdpData) {
            NSLog(@"80以后发送udp包");
            [self sendUdpData];
        }
    }
    if (nValue > 99) {
        [self unScheme];
        if (!isStopUdpData) {
            [[self class] cancelPreviousPerformRequestsWithTarget:self];
            UIAlertView *alertTemp = nil;
            if ([Global curLanguageEn]) {
                alertTemp = [[UIAlertView alloc] initWithTitle:@"" message:@"Failed" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Cancel", nil];
            }else{
                alertTemp = [[UIAlertView alloc] initWithTitle:@"" message:STR(@"配置失败") delegate:nil cancelButtonTitle:nil otherButtonTitles:STR(@"确定"), nil];
            }
            [alertTemp show];
        }
    }
}
-(void)unScheme{
    [sheet dismissWithClickedButtonIndex:0 animated:NO];
    sheet = nil;
    [timer invalidate]; timer = nil;
    [self.config stopTransmitting];
    self.config = nil;
}
-(void)dealloc{
    NSLog(@"");
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
    [NC removeObserver:self];
}

//- (void)alertView:(UIAlertView *)thisAlertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    if (thisAlertView.tag == 888) {
//        [self unScheme];
//        [[self class] cancelPreviousPerformRequestsWithTarget:self];
//    }
//}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    sheet = nil;
    [self unScheme];
    [[self class] cancelPreviousPerformRequestsWithTarget:self];
}
-(void)schemeBtnPressed:(UIButton*)btn{
    
    [[PokerControlClient share] stopc2sPing];
    
    isSendUdpData = NO;
    isStopUdpData = NO;
    
    if (!sheet) {
        NSString *msg = [NSString stringWithFormat:@"%@\n\n\n\n\n\n", STR(@"网络配置")];
        if ([Global curLanguageEn]) {
            msg = [NSString stringWithFormat:@"%@\n\n\n\n\n\n", STR(@" ")];
        }
        if ([Global curLanguageEn]) {
            sheet = [[UIActionSheet alloc] initWithTitle:msg delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:nil, nil];
        }else{
            sheet = [[UIActionSheet alloc] initWithTitle:msg delegate:self cancelButtonTitle:STR(@"取消") destructiveButtonTitle:nil otherButtonTitles:nil, nil];
        }
        [sheet showInView:self.view];
        
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        titleLabel.frame = CGRectMake(30, 40, SCREEN_WIDTH-30*2, 40);
        titleLabel.numberOfLines = 0;
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = [UIColor whiteColor];
        if (IOS7_OR_LATER) {
            titleLabel.textColor = [UIColor blackColor];
        }
        titleLabel.font = [UIFont systemFontOfSize:14.0f];
        titleLabel.text = STR(@"正在对设备进行配置，请稍等，该过程可能需要60秒");
        if ([Global curLanguageEn]) {
            titleLabel.text = @"Configuring...";
        }
        titleLabel.textAlignment = UITextAlignmentCenter;
        [sheet addSubview:titleLabel];
        
        progressLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        progressLabel.backgroundColor = [UIColor clearColor];
        progressLabel.textColor = [UIColor whiteColor];
        if (IOS7_OR_LATER) {
            progressLabel.textColor = [UIColor blackColor];
        }
        progressLabel.font = [UIFont systemFontOfSize:14.0f];
        progressLabel.textAlignment = UITextAlignmentCenter;
        [sheet addSubview:progressLabel];
        
        progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
        progressView.frame = CGRectMake(30, 35.f+45+20, SCREEN_WIDTH-30*2-30, 90.0f);
        [sheet addSubview:progressView];
        
        progressLabel.frame = CGRectMake(30+SCREEN_WIDTH-30*2-30+10, 40+20, 30, 90);
        if (IOS7_OR_LATER) {
            progressLabel.frame = CGRectMake(30+SCREEN_WIDTH-30*2-30+10, 40+20, 35, 90);
        }
        
    }
    [timer invalidate]; timer = nil;
    
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(incrementProgress:) userInfo:nil repeats:YES];
    [timer fire];
    

    [self.config stopTransmitting];
    self.config = nil;
    
    self.config = [[FirstTimeConfig alloc] initWithKey:m_tf2.text withEncryptionKey:nil];
    [self.config setDeviceName:@"CC3000"];
    [self.config transmitSettings];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    
    [NSThread detachNewThreadSelector:@selector(waitForAckThread:) toTarget:self withObject:nil];
}
-(void)resignActive{
    [self.config stopTransmitting];
}
-(void)becomeActive{
    [self.config transmitSettings];
}
-(void)stopUdpData{
    NSLog(@"停止发送udp包");
    isStopUdpData = YES;
}
-(void)sendUdpData{
    if (!isStopUdpData) {
        [self.config stopTransmitting];
        self.config = nil;
        int port = 15002;
        if (!self.udpSocket) {
            self.udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
            NSError *error = nil;
            [self.udpSocket enableBroadcast:YES error:&error];
            if (![self.udpSocket bindToPort:port error:&error]){
                NSLog(@"bindToPort error");
            }
        }
        [self.udpSocket receiveWithTimeout:-1 tag:0];
        NSString *sentip = @"255.255.255.255";
        NSString *dataStr = @"IFOProbeDevice";
        NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
        
        NSLog(@"SEND TO : %@:%d    %@", sentip, port, dataStr);
        [self.udpSocket sendData:data toHost:sentip port:port withTimeout:-1 tag:0];
        isSendUdpData = YES;
        [self performSelector:@selector(sendUdpData) withObject:nil afterDelay:.5];
    }else{
        [UD setObject:m_tf2.text forKey:WIFI_PASSWORD];
        [UD synchronize];
        
        [self unScheme];
        if ([Global curLanguageEn]) {
            UIAlertView *alertTemp = [[UIAlertView alloc] initWithTitle:@"" message:@"Successful Configuration" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alertTemp show];
        }else{
            UIAlertView *alertTemp = [[UIAlertView alloc] initWithTitle:@"" message:STR(@"配置成功") delegate:nil cancelButtonTitle:nil otherButtonTitles:STR(@"确定"), nil];
            [alertTemp show];
        }
    }
}
- (void) waitForAckThread: (id)sender{
    @try {
        NSLog(@"%s begin", __PRETTY_FUNCTION__);
        Boolean val = [config waitForAck];
        NSLog(@"Bool value == %d",val);
        if ( val ){
            [self stopAction];
            [self sendUdpData];
        }
    }
    @catch (NSException *exception) {
        NSLog(@"%s exception == %@",__FUNCTION__,[exception description]);
        /// stop here
    }
    @finally {
        
    }
    
    if ( [NSThread isMainThread]  == NO ){
        NSLog(@"this is not main thread");
        [NSThread exit];
    }else {
        NSLog(@"this is main thread");
    }
    NSLog(@"%s end", __PRETTY_FUNCTION__);
}
-(void) stopAction{
    NSLog(@"%s begin", __PRETTY_FUNCTION__);
    @try {
        [config stopTransmitting];
    }
    @catch (NSException *exception) {
        NSLog(@"%s exception == %@",__FUNCTION__,[exception description]);
    }
    @finally {
        
    }
    NSLog(@"%s end", __PRETTY_FUNCTION__);
}


@end


